import { sysLogin, sysProfile, sysUser } from '@/api/login'
import { constantRoutes, syncRountes } from '@/router'
import router from '@/router'
import { resetRouter } from '@/router'
//   import { setToken, getToken } from '@/utils/auth.js'
// import { Message } from 'element-ui'
const state = {
  username: '张三',
  token: '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    // setToken(value)
  },

  setUserInfo(state, value) {
    state.userInfo = value
  },
  logout(state) {
    state.token = ''
    state.userInfo = ''
    resetRouter()
    // 每一次退出登录都重置路由
  }
}
const actions = {
  async tologin({ commit }, value) {
    const res = await sysLogin(value)
    commit('setToken', res.data)
    console.log(res)
  },
  async getUserInfo(store) {
    //   注此处方法还没有调用
    const res = await sysProfile()
    console.log('用户信息', res)
    const res2 = await sysUser(res.data.userId)
    console.log('用户信息合并', res2)
    // 合并对象
    const info = Object.assign({}, res.data, res2.data)
    store.commit('setUserInfo', info)
    // 权限管理:动态路由中设置mate标签与用户信息所能获取权限管理页面所匹配
    // 将mate标签与用户含有的权限页面进行匹配
    // 用户含有页面权限可以进行展示,没有的则不展示

    const newArr = syncRountes.filter((item) => {
      return info.roles.menus.includes(item.meta.name)
    })
    newArr.push({ path: '*', redirect: '/404', hidden: true })

    store.commit('routes/setRoutes', [...constantRoutes, ...newArr], {
      root: true
    })
    router.addRoutes(newArr)
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
